﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ProgressUtil : MonoBehaviour {
	private Text autoText;
    private float nowValue;
    private float leftValue;
    private float maxValue;
	private Slider percentBar;
	public delegate void OnProgressDelegate(float progress);
	public OnProgressDelegate OnProgress;

    private Image previewFill;

    public float Progress
    {
        get
        {
            return nowValue / maxValue; ;
        }
    }

    public float RealProgress {
        get
        {
            return (nowValue + leftValue) / maxValue; ;
        }
    }

    public float MaxValue {
        get {
            return maxValue;
        }
    }

    public float RealNowValue {
        get{
            return nowValue + leftValue;
        }
    }

    public void SetPreviewFill(float progress) {
        if (previewFill) {
            previewFill.fillAmount = progress;
        }
    }

    // Use this for initialization
    void Awake () {
		autoText = gameObject.GetComponent<Text> ();
        //预览条对象如果有，就保存下来
        Transform previewFillTrans = transform.Find("Fill Area/PreviewFill");
        if (previewFillTrans) {
            previewFill = previewFillTrans.GetComponent<Image>();
        }
        
        leftValue = 0;
		percentBar = GetComponent<Slider> ();
		StartCoroutine (RunAddNum ());
	}
	
	public void Init(float addValue,float maxValue){
		nowValue = 0;
		leftValue = addValue;
		this.maxValue = maxValue;
		percentBar.value = 0f;
	}

    public void Reset() {
        nowValue = 0;
        leftValue = 0;
        percentBar.value = 0;
        SetPreviewFill(0);
    }

	void SetPercent(){
		if(percentBar != null){
			if(nowValue < 0){
				nowValue = 0;
				if(leftValue < 0)
					leftValue = 0;
			}
			maxValue = maxValue == 0 ? 1 : maxValue;
			percentBar.value = Progress;
			if(OnProgress != null){
				OnProgress(Progress);
			}
		}
	}
	
	public void AddPercent(float addValue){
		if (Progress >= 1) {
			leftValue = 0;
		} else {
			leftValue += addValue;
		}
	}
	
	public IEnumerator RunAddNum(){
		while (true) {
			if(Mathf.Abs(leftValue) > 0) {
				float offset = leftValue > 0 ? 1f : -1f;
				float baseValue = maxValue / 50 * offset;
				baseValue = Mathf.Abs(baseValue) > Mathf.Abs(leftValue) ? leftValue : baseValue;
				nowValue += baseValue;
				leftValue -= baseValue;
				if (nowValue >= maxValue) {
					nowValue += leftValue;
					leftValue = 0f;
				}else if(nowValue < 0){
					nowValue = 0;
					if(leftValue < 0){
						leftValue = 0;
					}
				}

                if (autoText != null) {
					autoText.text = nowValue + "";
				}
				SetPercent ();
			}
			yield return null;
		}
	}
	
}
